package cn.cumt.lkk.webapp.controller;

import cn.cumt.lkk.dao.LinkDao;
import cn.cumt.lkk.model.Link;
import cn.cumt.lkk.service.LinkManager;
import cn.cumt.lkk.webapp.validator.LinkValidator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * Created by lkk on 2015/4/30.
 */
@Controller
@RequestMapping("/linkform*")
public class LinkFormController extends BaseFormController {

    LinkManager linkManager;

    @Autowired
    public void setLinkManager(@Qualifier("linkManager") LinkManager linkManager) {
        this.linkManager = linkManager;
    }

    public LinkFormController() {
        setCancelView("redirect:/links");
        setSuccessView("redirect:/links");

    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setValidator(new LinkValidator());
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.GET)
    protected Link showForm(@RequestParam(required = false) String id) {
        if (!StringUtils.isBlank(id)) {
            return linkManager.get(Long.valueOf(id));
        }
        return new Link();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(@Validated Link link, BindingResult errors, HttpServletRequest request) {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (errors.hasErrors() && request.getParameter("delete") == null)
            return "linkform";

        boolean isNew = link.getId() == null;
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            linkManager.remove(link.getId());
            saveMessage(request, getText("link.delete", locale));
        } else {
            link = linkManager.save(link);
            saveMessage(request, getText("link." + (isNew ? "edit" : "new"), locale));
            if (isNew)
                success = "redirect:/linkform?id=" + link.getId();
        }

        return success;
    }
}
